package top.zsyle.movie.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.zsyle.movie.result.JsonResult;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * Exception系统异常错误信息
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public JsonResult exceptionHandler(Exception e){
        e.printStackTrace();
        log.error("Exception系统异常错误信息：{}",e.getMessage());
        return JsonResult.error(GlobalExceptionEnum.ERROR.getMessage());
    }

    /**
     * GlobalException自定义异常错误信息
     * @param e
     * @return
     */
    @ExceptionHandler(GlobalException.class)
    public JsonResult globalExceptionHandler(GlobalException e){
        e.printStackTrace();
        log.error("GlobalException自定义异常错误信息：{}，错误码：{}",e.getMessage(),e.getCode());
        return JsonResult.error(e.getMessage(), e.getCode());
    }

    /**
     * methodArgumentNotValidException:JSR303注解异常错误信息
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        StringBuilder sb = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(error-> sb.append(error.getDefaultMessage()).append(";"));
        log.error("methodArgumentNotValidException：JSR303注解异常错误信息：{}，错误码：{}",sb,GlobalExceptionEnum.PARAM_VALIDATION_EXCEPTION.getCode());
        return JsonResult.error(sb.toString(),GlobalExceptionEnum.PARAM_VALIDATION_EXCEPTION.getCode());
    }


}
